package com.zzgele.qmzb.api.web;

import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import com.zzgele.qmzb.api.core.ResultGenerator;
import com.zzgele.qmzb.api.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
* Created by Martin on 2017/07/09.
*/
@RestController
@RequestMapping("/file")
public class FileController {
    private final Logger logger = LoggerFactory.getLogger(FileController.class);

    /**
     * 文件上传根目录(在Spring的application.yml的配置文件中配置):<br>
     * web:
     *  upload-path: （jar包所在目录）/resources/static/
     */
    @Value("${web.upload-path}")
    private String webUploadPath;

    @PostMapping(value="/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result upload(Long login_uid, MultipartFile file) {
        if (file.isEmpty()) {
            return ResultGenerator.genFailResult("上传失败：请选择要上传的图片!");
        }

        try {
            if (!file.getContentType().contains("image")) {
                return ResultGenerator.genFailResult("上传失败：上传的文件不是图片类型，请重新上传!");
            }

            String fileName = file.getOriginalFilename();
            // 获取图片的扩展名
            String extensionName = StringUtils.substringAfter(fileName, ".");
            // 新的图片文件名 = 获取时间戳+"."图片扩展名
            String newFileName = StringUtil.getFielName();
            String newFileFullName = newFileName + "." + extensionName;
            // 数据库保存的目录
            String UploadDirectory = String.valueOf(login_uid).concat(File.separator);
            // 文件路径
            String filePath = webUploadPath.concat(UploadDirectory);

            File dest = new File(filePath, newFileFullName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 上传到指定目录
            file.transferTo(dest);

            // 将图片流转换进行BASE64加码
            //BASE64Encoder encoder = new BASE64Encoder();
            //String data = encoder.encode(file.getBytes());

            // 将反斜杠转换为正斜杠
            String data = UploadDirectory.replaceAll("\\\\", "/") + newFileFullName;
            data = Constants.STATIC_URL_UPLOAD.concat(data);
            HashMap hashMap = new HashMap();
            hashMap.put("url", data);
            return ResultGenerator.genSuccessResult(hashMap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("上传失败：" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("上传失败：" + e.getMessage());
        }
    }
}
